<template>
  <div class="app-container">
    <upload-excel-component
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
    <el-table
      :data="tableData"
      border
      highlight-current-row
      style="width: 100%;margin-top:20px;"
    >
      <el-table-column
        v-for="item of tableHeader"
        :key="item"
        :prop="item"
        :label="item"
      />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { importEmployeeAPI } from '@/api'
import { formatExcelDate } from '@/utils'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data () {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload (file) {
      // 判断传入的是否小于1MB
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true // 通过
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      }) // 不通过,返回false,并提示
      return false
    },
    async handleSuccess ({ results, header }) {
      console.log(results, header)
      this.tableData = results
      this.tableHeader = header
      // results:表格的所有数据, header:第一行(作为列的标题)
      //   results 数组套对象,每个对象对应一行数据
      //   注:后台需要英文,所以需要做一个后置处理
      //   xlsx读中文的对象数据,拿到后做一个转换
      // 1.准备中文换英文的映射关系(枚举对象)

      const userRelations = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName',
        聘用形式: 'formOfEmployment'
      }
      // Object.keys(对象) -> 返回对象里所有key字符串数组
      const aa = results.map(obj => {
        const newArr = {}
        const keyArr = Object.keys(obj)
        keyArr.forEach(zhKeys => {
          const unKeys = userRelations[zhKeys] // 英文的key

          if (unKeys === 'timeOfEntry' || unKeys === 'correctionTime') {
            const transDate = formatExcelDate(obj[zhKeys])
            // 再把日期对象转成->'年-月-日'保存到对象属性里给后台
            newArr[unKeys] = transDate
          } else {
            newArr[unKeys] = obj[zhKeys]
          }
        })
        return newArr
      })
      console.log(aa)
      const res = await importEmployeeAPI(aa)
      this.$message.success(res.message)
      this.$router.back()
    }
  }
}
</script>
